#include <qqtvirtuallongdataservermanager.h>

#include <qqthostaddressmanager.h>

QQtVirtualLongDataServerManager::QQtVirtualLongDataServerManager ( QObject* parent )
    : QObject ( parent )
{
    s0 = 0;
    m0 = 0;
}

QQtVirtualLongDataServerManager::~QQtVirtualLongDataServerManager() {}

void QQtVirtualLongDataServerManager::setServerHandler ( QQtUdpServer* handler )
{
    s0 = handler;
}

QQtUdpServer* QQtVirtualLongDataServerManager::handler()
{
    return s0;
}

void QQtVirtualLongDataServerManager::setProtocolManagerHandler ( QQtProtocolManager* pm )
{
    m0 = pm;

    s0->installProtocolManager ( m0 );
    connect ( m0, SIGNAL ( notifyToBusinessLevel ( const QQtProtocol*, const QQtMessage* ) ),
              this, SLOT ( notifyToUser ( const QQtProtocol*, const QQtMessage* ) ) );

    connect ( m0, SIGNAL ( remainingProtocolChanged ( int ) ),
              this, SLOT ( remainingProtocolChanged ( int ) ) );
}

QQtProtocolManager* QQtVirtualLongDataServerManager::protocolManager()
{
    return m0;
}

void QQtVirtualLongDataServerManager::notifyToUser ( QQtProtocol* protocol, QQtMessage* message )
{
    //用户感兴趣的消息。
    //UserServerLongDataProtocol * p0 = (UserServerLongDataProtocol*)protocol;
    //QQtLongDataSerialization& ds0 = (QQtLongDataSerialization&)*message;
}

void QQtVirtualLongDataServerManager::remainingProtocolChanged ( int num )
{
    if ( num > 10 )
        return;
    //m0->registerProtocol<UserServerProtocol>();
}

void QQtVirtualLongDataServerManager::setServerAddress ( QHostAddress address, int port )
{
    s0->setServerAddress ( address, port );
    p3line() << address.toString() << port;
}

void QQtVirtualLongDataServerManager::setServerPort ( int port )
{
    s0->setServerAddress ( QHostAddress ( QHostAddress::Broadcast ), port );
    p3line() << QHostAddress ( QHostAddress::Broadcast ) << port;
}

void QQtVirtualLongDataServerManager::setListeningAddress ( QHostAddress address, int port )
{
    s0->disconnectFromHost();
    s0->bind ( address, port, QQtUdpClient::DefaultForPlatform );
    p3line() << s0->localAddress() << s0->localPort();
}

void QQtVirtualLongDataServerManager::setListeningPort ( int port )
{
    s0->disconnectFromHost();
    QQtHostAddressManager manager;
    QString ip = manager.getHostAddress();
#if USE_HOST_ADDRESS
    s0->bind ( QHostAddress ( ip ), port, QQtUdpClient::DefaultForPlatform );
#else
    s0->bind ( port, QQtUdpClient::DefaultForPlatform );
#endif
    p3line() << s0->localAddress() << s0->localPort();
}
